# _*_ coding:utf-8 _*_
# @File  : advertisement.py
# @Time  : 2020-10-13 13:48
# @Author: zizle
""" 广告相关API
1- 创建一个新的广告
"""
import os
import hashlib
import datetime
from fastapi import APIRouter, Form, UploadFile, Depends, HTTPException, Query, Path
from utils.verify import oauth2_scheme, decipher_user_token
from utils.file import generate_unique_filename
from db.mysql_z import MySqlZ
from db import FAConnection
from configs import FILE_STORAGE, WEB_HOST
from status import r_status
from interfaces.depends import admin_logged_require

advertisement_api = APIRouter()


@advertisement_api.post("/advertisement/", summary="创建一个新的广告")
async def create_advertisement(
        person: dict = Depends(admin_logged_require),
        image: UploadFile = Form(...),
        pdf_file: UploadFile = Form(None),
        title: str = Form(...),
        ad_type: str = Form(...),
        web_url: str = Form(''),
        content: str = Form(''),
        note: str = Form(''),
):
    # 验证用户写入数据库
    user_id = person['uid']
    # 验证ad_type
    if ad_type not in ["file", "web", "content"]:
        raise HTTPException(status_code=400, detail="Unknown Advertisement Type!")
    # 创建广告文件保存的文件夹
    image_folder = os.path.join(FILE_STORAGE, "ADVERTISEMENT/Image/")
    file_folder = os.path.join(FILE_STORAGE, "ADVERTISEMENT/File/")
    if not os.path.exists(image_folder):
        os.makedirs(image_folder)
    if not os.path.exists(file_folder):
        os.makedirs(file_folder)
    # 生成filename
    img_name = hashlib.md5(str(datetime.datetime.now().timestamp()).encode('utf8')).hexdigest()
    save_folder, new_filename, _ = generate_unique_filename(image_folder, img_name, 'png')
    image_path = os.path.join(save_folder, f'{new_filename}.png')
    image_sql_path = os.path.join("ADVERTISEMENT/Image/", f'{new_filename}.png')
    pdf_path, pdf_sql_path = '', ''
    if pdf_file:
        pdf_name = hashlib.md5(str(datetime.datetime.now().timestamp()).encode('utf8')).hexdigest()
        pdf_folder, pdf_filename, _ = generate_unique_filename(file_folder, pdf_name, '.pdf')
        pdf_path = os.path.join(pdf_folder, f'{pdf_filename}.pdf')
        pdf_sql_path = os.path.join("ADVERTISEMENT/File/", f'{pdf_filename}.pdf')
    # 数据保存并入库
    db = FAConnection(conn_name='新建广告')
    sql = 'INSERT INTO info_advertisement (creator,title,ad_type,image,filepath,web_url,content,note) ' \
          'VALUES (%s,%s,%s,%s,%s,%s,%s,%s);'
    db.insert(sql, param=[user_id, title, ad_type, image_sql_path, pdf_sql_path, web_url, content, note])
    # 保存文件
    image_content = await image.read()  # 将文件保存到目标位置
    with open(image_path, "wb") as fp:
        fp.write(image_content)
    await image.close()
    if pdf_file:
        pdf_content = await pdf_file.read()
        with open(pdf_path, "wb") as fp:
            fp.write(pdf_content)
        await pdf_file.close()
    return {'code': r_status.CREATED_SUCCESS, 'message': '创建新广告成功!'}


@advertisement_api.get("/advertisement/", summary="获取系统中所有广告信息")
async def get_advertisements():
    db = FAConnection(conn_name='查询广告')
    sql = 'SELECT a.id,a.create_time,a.creator,b.username,a.title,a.ad_type,a.image,a.filepath,a.web_url,' \
          'a.content,a.note,a.is_active ' \
          'FROM info_advertisement AS a ' \
          'INNER JOIN user_user AS b ON a.creator=b.id ' \
          'ORDER BY a.create_time DESC;'
    advertisements = db.query(sql)
    for ad in advertisements:
        ad['create_time'] = ad['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        if ad['filepath']:
            ad['filepath'] = WEB_HOST + ad['filepath']
        ad['image'] = WEB_HOST + ad['image']
    return {"code": r_status.SUCCESS, "message": "查询成功!", "data": advertisements}


@advertisement_api.put("/advertisement/{ad_id}/", summary="修改广告的启用与否")
async def modify_advertisement_active(person: dict = Depends(admin_logged_require), ad_id: int = Path(..., ge=0),
                                      is_active: int = Query(..., ge=0, le=1)):
    db = FAConnection(conn_name='设置广告启用')
    _, success = db.execute('UPDATE info_advertisement SET is_active=%s WHERE id=%s;', param=[is_active, ad_id])
    if success:
        return {'code': r_status.SUCCESS, 'message': '设置成功!'}
    return {'code': r_status.UNKNOWN_ERROR, 'message': '设置失败了!'}
